<script setup>

import MyNav from "@/components/MyNav.vue";

import MyHead from "@/components/MyHead.vue";

import MyTable from "@/components/MyTable.vue";

import {onMounted, ref, shallowReactive, shallowRef} from "vue";

import {dateFormat, myRemove, myPage, myRemoveBatch, genderFormat, elConfirm, getResponseData} from "@/util";

import {
  getRolesApi,
  listApi,
  pageApi,
  pageLikeNicknameApi,
  removeApi,
  removeBatchApi,
  resetPasswordApi
} from "@/api/EmpApi";

import MyPager from "@/components/MyPager.vue";

import MyList from "@/components/MyList.vue";

import {excelApi} from "@/api/axios";

import router from "@/router";

import {MINIO_HOST} from "@/const";

import MyUploader from "@/components/MyUploader";
import {useStore} from "vuex";
import {ElMessage} from "element-plus";

// 表格记录 + 主键数组 + 分页信息 + 详情抽屉 +上传头像 + 详情列表

let records = ref();

let ids = [];

let pageInfo = shallowReactive({'pageNum': 1, 'pageSize': 5, 'fn': page});

let detailDrawer = shallowRef();

let rolesDrawer = shallowRef();

let uploadDrawer = shallowRef();

let detailItems = ref();

let empNickname = shallowRef();

/* ==================== 我的角色 ==================== */
function toEmpRoles(row){
  router.push({'path':'/ums/EmpRoles', query: {'empId': row['id']}})
}


/* ==================== 重置密码 ==================== */
async function resetPassword(row) {

  //获取当前登录的员工
  let loginEmp = JSON.parse(sessionStorage.getItem('loginEmp'));
  // 危险操作保护
  if (!await elConfirm('是否要重置密码？')) return;
  let res = await resetPasswordApi(row['id']);
  let data = getResponseData(res);
  if (data) {
    ElMessage.success('密码重置为${data}！');
    // 若重置的是当前登录的员工，则跳入登录页面
    if (loginEmp['id'] === row['id']) {
      ElMessage.success('重置了当前登录的员工密码，请重新登录！');
      setTimeout(() => router.push('/'), 1000);
    }
    // 否则重新分页
    else {
      await page();
    }
  }
}

/* ==================== 上传头像 ==================== */
let uploadUrl = shallowRef();
// 当前操作记录的ID
let currentId;

// 上传头像：打开抽屉 > 发送请求
function upload(row) {
  uploadDrawer.value = true;
  currentId = row['id'];
  uploadUrl.value = 'http://localhost:8101/api/v1/emp/uploadAvatar?id=' + row['id'];
}

// 上传成功：关闭抽屉 > 重新登录或重新分页
function uploadSuccess() {
  uploadDrawer.value = false;
  //获取当前登录的员工
  let loginEmp = JSON.parse(sessionStorage.getItem('loginEmp'));
  // 若修改的是当前登录的员工，则跳入登录页面
  if (loginEmp['id'] === currentId) {
    ElMessage.success('修改了当前登录的员工信息，请重新登录！');
    setTimeout(() => router.push('/'), 1000);
  }
  // 否则重新分页
  else {
    page();
  }
}
/* ==================== 分页查询 ==================== */

async function page(pageNum = pageInfo['pageNum'],

                    pageSize = pageInfo['pageSize']) {

  let config = {

    'api': pageApi,

    'params': {'pageNum': pageNum, 'pageSize': pageSize},

    'records': records,

    'pageInfo': pageInfo

  }



  // 搜索员工名

  if (empNickname.value) {

    config['params']['realname'] = empNickname.value;

    config['api'] = pageLikeNicknameApi;

  }



  // 发送分页请求

  await myPage(config);

}



/* ==================== 单条修改 ==================== */

function update(record) {

  sessionStorage.setItem('emp', JSON.stringify(record));

  router.push('/ums/EmpUpdate');

}
/* ==================== 修改记录 ==================== */
function updateSuccess(){
  //获取当前登录的员工
  let loginEmp = JSON.parse(sessionStorage.getItem('loginEmp'));
  //若修改的是当前登陆的员工,则跳入登陆页面
  if(loginEmp['id'] === emp['id']){
    sessionStorage.clear();
    let vuex = useStore();
    vuex.dispatch('setLoginFlag', false);
    router.push('/');
  }
  //否则跳入Emp列表界面
  else {
    router.push('/ums/Emp');
  }
}


/* ==================== 单条删除 ==================== */

async function remove(record) {

  await myRemove({

    'id': record['id'],

    'api': removeApi,

    'fn': page

  });

}



/* ==================== 批量删除 ==================== */

async function removeBatch() {

  await myRemoveBatch({

    'ids': ids,

    'api': removeBatchApi,

    'fn': page

  });

}



/* ==================== 搜索员工名 ==================== */

function pageByNickname(record) {

  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求

  if (record || empNickname.value) {

    empNickname.value = record;

    page();

  }

}



/* ==================== 查看详情 ==================== */

function detail(record) {

  detailItems.value = [

    {

      'label': '员工头像', 'value': record['avatar'], 'type': 'img',

      minio: url => MINIO_HOST + '/avatar/' + url

    },

    {'label': '登录账号', 'value': record['username']},

    {'label': '手机号码', 'value': record['phone']},

    {'label': '微信号码', 'value': record['wechat']},

    {'label': '电子邮件', 'value': record['email']},

    {'label': '员工性别', 'value': record['gender'], 'format': genderFormat},

    {'label': '员工年龄', 'value': record['age']},

    {'label': '所在省份', 'value': record['province']},

    {'label': '详细地址', 'value': record['address']},

    {'label': '真实姓名', 'value': record['realname']},

    {'label': '身份证号', 'value': record['idcard']},

    {'label': '所在部门' , 'value': record['dept'] ? record['dept']['title'] : '暂未分配部门'},

    {'label': '入职日期', 'value': record['hiredate'], 'format': dateFormat},

    {'label': '创建时间', 'value': record['created'], 'format': dateFormat},

    {'label': '修改时间', 'value': record['updated'], 'format': dateFormat},

    {'label': '员工描述', 'value': record['info'], 'type': 'card'},

  ];

  detailDrawer.value = true;

}



/* ==================== 加载函数 ==================== */

onMounted(() => page());



</script>



<template>



  <my-nav :items="[

  {'icon': 'User', 'label': '员工管理'},

  {'icon': 'User', 'label': '员工列表'},

]"/>



  <my-head :items="[

  {'type': 'ipt', 'span': 5, 'placeholder': '员工名称', 'fn': pageByNickname},

  {'type': 'insertBtn', 'offset': 16, 'fn': () => router.push('/ums/EmpInsert')},

  {'type': 'deleteBtn', 'fn': removeBatch},

  {'type': 'excelBtn', 'fn': () => excelApi('/emp/excel', '员工统计表')},

]"/>



  <my-table v-if="records" :records="records" :columns="[

    {'column': '员工头像', 'property': 'avatar', 'type':'img',

      minio: url => MINIO_HOST + '/avatar/' + url},

    {'column': '登录账号', 'property': 'username'},

    {'column': '手机号码', 'property': 'phone'},

    {'column': '微信号码', 'property': 'wechat'},

    {'column': '电子邮件', 'property': 'email'},

    {'column': '员工性别', 'property': 'gender','format': genderFormat},

    {'column': '员工年龄', 'property': 'age'},

    {'column': '所在省份', 'property': 'province'},

    {'column': '详细地址', 'property': 'address'},

    {'column': '真实姓名', 'property': 'realname'},

    {'column': '身份证号', 'property': 'idcard'},

    {'column': '所在部门', 'property': 'dept.title'},

    {'column': '入职日期', 'property': 'hiredate', 'format': dateFormat},

    {'column': '创建时间', 'property': 'created', 'format': dateFormat},

    {'column': '修改时间', 'property': 'updated', 'format': dateFormat},

    {'column': '员工描述', 'property': 'info', 'type': 'card'},

]" :buttons="[

  {'type': 'info', 'fn': detail},

  {'type': 'update', 'fn': update},

  {'type': 'delete', 'fn': remove},

  {'type': 'upload', 'btnLabel': '上传头像', 'fn': upload},

  {'btnLabel': '我的角色', 'btnType': 'warning','fn': toEmpRoles},

  {'btnLabel': '重置密码','btnIcon': 'User', 'fn': resetPassword},

]" :selection-change="rows => ids = rows.map(e => e['id'])"/>



  <my-pager v-if="records" :page-info="pageInfo"/>



  <el-drawer v-model="detailDrawer" size="30%">

    <my-list title="记录详情" :items="detailItems"/>

  </el-drawer>

  <el-drawer title="上传头像" v-model="uploadDrawer" size="30%">

    <my-uploader :action="uploadUrl" name="avatarFile" :fn="uploadSuccess"/>

  </el-drawer>





</template>



<style scoped lang="scss">



</style>